package com.fivetalks.controller.web;

import javax.validation.Valid;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.fivetalks.domain.SecurityUser;
import com.fivetalks.domain.User;
import com.fivetalks.security.annotation.AuthUser;
import com.fivetalks.service.UserService;


@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MessageSource messageSource;
	
	@RequestMapping( value = "/user/signup", method = RequestMethod.GET , headers = { "Accept=text/html" })
	public String getSignup( @AuthUser SecurityUser securityUser, Model model ){
		System.out.println("/user/signup");
		model.addAttribute("user", new User());
		return ( securityUser == null) ? ( "/user/signup" ) : ( "redirect:/" ); 
	}
	
	@RequestMapping( value = "/user/join", method = RequestMethod.POST, headers = { "Accept=text/html" }  )
	public String join( @ModelAttribute("user") @Valid User user, BindingResult bindingResult) {
		

		if ( bindingResult.hasErrors() ) {
			return ( "/user/signup" );
		}
		
		// 이메일 중복 
		if( userService.emailExists( user.getEmail() ) == true ) {
			return ( "/user/signup" );
		}
		
		// 닉네임 중복
		if( userService.nicknameExists( user.getNickname() )  == true ) {
			return ( "/user/signup" );
		}
		
		// 저장
		userService.addUser( user );
		
		// 성공 -> 웰컴 리다이렉트! 
		return ( "redirect:/user/welcome" );
	}
	
	@RequestMapping( value = "/user/welcome", method = RequestMethod.GET, headers = { "Accept=text/html" } )
	public String welcome( @RequestHeader( value = "referer", required = false ) final String referer, @AuthUser SecurityUser securityUser ) {
		return ( securityUser != null || referer == null )  ?  "redirect:/" : "/user/welcome";
	}
	
	@RequestMapping( value = "/user/list", method = RequestMethod.GET, headers = { "Accept=text/html" } )
	public void list( Model model ) {
		model.addAttribute("users", userService.getAllUser() );		
	}
	
}